/**
 *  auth: Wayne
 *  function: 设备接口
 * */

let express = require('express');
let router = express.Router();
let exportflag = require("../model/exportflag");
let util=require("../util/util");


/**
 * @function 新增vps
 * @author wayne
 * @date 2019-02-19
 * @param
 */
router.post('/add',function (req,res) {
  //const newObj = new exportflag(req.body);
  const newObj = new exportflag();
  let name = 'flag';
  newObj.name=name;
  newObj.flag='true'
  let findparams={
    name:name
  }
  if(name){
    exportflag.find(findparams, (err,results)=> {
      if(err){
        res.send(util.reObj(-1,'添加失败',err))
      }else {
        if(results.length>0){
          res.send(util.reObj(-2,'exist'))
        }else{
          newObj.save( (err, result)=>{
            if(err){
              res.send(util.reObj(-1,'添加失败'))
            }else{
              res.send(util.reObj(0,'添加成功',result))
            }
          })
        }
      }
    })
  }else{
    res.send(util.reObj(-1,'轮播图名称不能为空'))
  }


})
/**
 * @function 删除exportflag
 * @author wayne
 * @date 2019-02-19
 * @param
 */
router.post('/del',function (req,res) {
  let udid = req.body.name,
      params={
        name:name
      };
  if(name) {
    exportflag.remove(params,(err,result)=>{
      if (err) {
        res.send(util.reObj(-1,'del error'))
      }
      else {
        res.send(util.reObj(0,'success'))
      }
    })

  }else{
    res.send(util.reObj(-1,'exportflagid can not be null'))
  }

})
/**
 * @function 查询exportflag
 * @author wayne
 * @date 2019-02-19
 * @param
 */
router.get('/find',async (req,res)=>{
  let param={},
      skipnum=req.query.skipnum||0,
      pagesize=req.query.pagesize||10;

  const reg = new RegExp(req.query.udid, 'i') //不区分大小写
  if(req.query.udid)
  {
    param.name={$regex : reg}
  }

  try {
    const results = await exportflag.find(param,null,{skip: parseInt(skipnum), limit:parseInt(pagesize),sort: {register_time: -1}})
    const count =await exportflag.count(param,null,{skip: parseInt(skipnum), limit:parseInt(pagesize),sort: {register_time: -1}})
    res.send(util.reObj("0",'success',results,count))
  }
  catch (err) {
    res.send(util.reObj(-1,'failed',err))
  }



})


/**
 * @function 修改vps
 * @author wayne
 * @date 2017-11-20
 * @param
 */
router.get('/update',function (req,res) {
  let name = 'flag',
      flag = 'false'

  let findparams={
    name:name
  }
  let updateparams={
    flag:flag
  }
  for (var key of Object.keys(updateparams)) {
    if(!updateparams[key])
      delete updateparams[key]
  }
  if(name){
    exportflag.findOneAndUpdate(findparams,{$set:{flag:flag}},function (err,result) {
      if(err){
        res.send(util.reObj(-1,'failed',err))
      }else{
        res.send(util.reObj(0,'success',result))
      }
    })
  }else{
    res.send(util.reObj(-1,'vpsid can not be null,undefined,empty'))
  }
})


module.exports = router;
